<?
	session_start(); if (!$_SESSION['logged']) {header("Location: index.php"); die();}

	$section_dir = "/user/sections/";

//	include_once ('../core/class.upload.php');
	include_once ('../core/adds.php');

//	echo "<pre>"; print_r ($_POST); echo "</pre>";

	if (!empty($_POST['item_id_order'])) {
		include ('../user/counter_sct.php');
		$sect_ids=explode(",",$sect_ids_string);

		// этот блок нужен для добавления новых отзывов
		foreach ($_POST as $k => $v) {
			$tmp = preg_match("/section_([0-9]+)_name/",$k,$matches);
			if (($tmp > 0)&&(!in_array($matches[1],$sect_ids))) {
				$sect_ids[] = $matches[1];
				if (empty($_POST['section_'.$matches[1].'_name'])) $_POST['section_'.$matches[1].'_name'] = "название";
				// создаем файл sectN.php для новой секции
				file_put_contents("..".$section_dir."sect".$matches[1].".php","содержимое секции");
			}
			$sect_ids = array_unique($sect_ids);
		}

		$tmp = array_map("rem_item_order_trash",explode("&",$_POST['item_id_order']));
		$sect_order = array_combine(array_values($tmp),array_keys($tmp));
		$field_kind = array('name');

		$sect2delete = array();
		$out_file = '';
		$new_pos = '1000'; // для новых элементов берем фонарное значение позиции, так чтоб было последним
		include ('../user/section.php');

		foreach ($sect_ids as $s_id) {
			// если не пришло имя - элемент считаем удаленным
			if (empty($_POST['section_'.$s_id.'_name'])) {
				$sect2delete[] = $s_id;
				continue;
			}
			// заполняем информацию по основным полям
			foreach ($field_kind as $fk) // имя, контакт, отзыв
				$out_file .= "\t".'$section_'.$s_id.'_'.$fk.' = "'
							.htmlspecialchars($_POST['section_'.$s_id.'_'.$fk]).'";'."\n";

			$out_file .= "\t".'$section_'.$s_id.'_pos = "'.$sect_order[$s_id].'";'."\n";
			$out_file .= "\n";
		}
		// сохраняем обновленный список id-шников
		$res_sect_ids = implode(",",array_diff($sect_ids,$sect2delete));
		if (file_exists('../user/counter_sct.php'))
			rename('../user/counter_sct.php','../user/backups/bak_counter_sct_'.date('YmdHis').'.php')
			or die('Не удалось создать резервную копию counter_sct.php!');
		file_put_contents('../user/counter_sct.php','<? $sect_ids_string="'.$res_sect_ids.'"; ?>');

		// сохраняем сами названия секций
		$out_file = "<?\n" . $out_file . "?>";
		if (file_exists('../user/section.php'))
			rename('../user/section.php','../user/backups/bak_section_'.date('YmdHis').'.php')
			or die('Не удалось создать резервную копию section.php!');
		file_put_contents('../user/section.php',$out_file);
	}

	$mnemonics = array('#SECT_ID#');
	$section_template = '	<tr id="#SECT_ID#" class="id">
		<td class="del_item_row"><a class="small_button" onclick="del_item(#SECT_ID#)"><span>del</span></a></td>
		<td class="dragHandle"></td>
		<td class="value">
			<table>
				<tr>
					<td>Название</td>
					<td><input name="section_#SECT_ID#_name" type="text" value="<?=${"section_#SECT_ID#_name"}?>"></td>
					<td><? echo \'<a class="small_button edit_btn" href="edit_section.php?section_id=#SECT_ID#" style="width:130px"><span>редактировать</span></a>\';?></td>
				</tr>
			</table>
		</td>
	</tr>';


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"[]>
<html lang="ru-RU">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Редактирование секций</title>
    <link rel="stylesheet" href="/core/reset.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/adm/adm_style.css" type="text/css" media="screen" />
    <!--[if IE 6]><link rel="stylesheet" href="/core/style.ie6.css" type="text/css" media="screen" /><![endif]-->
    <!--[if IE 7]><link rel="stylesheet" href="/core/style.ie7.css" type="text/css" media="screen" /><![endif]-->
	<script type="text/javascript" src="/core/jquery.js"></script>
	<script type="text/javascript" src="/core/jquery.tablednd_0_5.js"></script>
	<script type="text/javascript" src="/core/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
	<link rel="stylesheet" type="text/css" href="/core/fancybox/jquery.fancybox-1.3.4.css" media="screen" />
	<script>
		$(document).ready(function() {
			$("#item_id").tableDnD({
				dragHandle: "dragHandle"
			});

			$("#item_id tr.id").hover(function() {
				$(this.cells[1]).addClass('showDragHandle');
			}, function() {
				$(this.cells[1]).removeClass('showDragHandle');
			});

			$("a.edit_btn").fancybox({
				'width'				: 786,
				'height'			: 520,
				'autoScale'			: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe'
			});
		});

		function add_item() {
			var new_id = $('#last_id').val()*1 + 1;
			$('#last_id').val(new_id);
//			var tmp = document.getElementById('item_id').getElementsByTagName('TBODY')[0].innerHTML;
			$('#item_id_body').append('<?=preg_replace("/\<\?((?!\?\>).)*\?\>/","",str_replace(array("\r","\n"),"",$section_template))?>'.replace(/#SECT_ID#/g,new_id));
			$("#item_id").tableDnDUpdate();
			$("#item_id tr.id").hover(function() {
				$(this.cells[1]).addClass('showDragHandle');
			}, function() {
				$(this.cells[1]).removeClass('showDragHandle');
			});
			$("input[name='section_"+new_id+"_name']").focus();
		}

		function del_item(item_id) {
			if (confirm('Вы действительно хотите удалить секцию "'
				+$("input[name='section_"+item_id+"_name']").val()+'"?')) {
					$("#"+item_id).remove()
			}
		}
	</script>
</head>

<body style="min-width:500px;">
<?php
	include ('../user/section.php');
?>
<div id="make_section">
<form name="section_form" enctype="multipart/form-data" action="make_section.php" method="post"
	onsubmit="document.getElementById('item_id_order').value = $('#item_id').tableDnDSerialize();">
<input name="item_id_order" id="item_id_order" type="hidden" value="">
<span class="cfg_section_name">Дополнительные секции</span>
<a class="button" onclick="$('form[name=section_form]').submit();"><span>Сохранить</span></a><br /><br /><br />
<table class="adm_table" id="item_id"><tbody id="item_id_body">
<?
	include ('../user/counter_sct.php');
	$sect_ids = explode(",",$sect_ids_string);

	$sect2show = array();
	foreach ($sect_ids as $sect_id) $sect2show[${"section_".$sect_id."_pos"}] = $sect_id;
	$resp_max_id = $sect_id;
	if (!empty($sect2show)) {
		ksort($sect2show,SORT_NUMERIC);
		foreach ($sect2show as $sect_id) {
			$cur_template = $section_template;
			foreach ($mnemonics as $mnem) {
				$cur_template = str_replace($mnem,${strtolower(substr($mnem,1,-1))},$cur_template);
			}
			eval ('?>'.$cur_template.'<?');
		}
	}
?>
</tbody>
</table><br />
<input id="last_id" type="hidden" value="<?=$resp_max_id?>">
<a class="button" onclick="$('form[name=section_form]').submit();"><span>Сохранить</span></a>&nbsp;&nbsp;&nbsp;

<a class="button" onclick="add_item()"><span>Добавить</span></a>
</form>
</div>
</body>

</html>